﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using Microsoft.Web.Administration;

using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.PowerShell;

namespace Mystery.SharePoint.PowerShell
{
    [SPCmdlet(RequireUserFarmAdmin = true)]
    [Cmdlet("Add", "SPMIisBinding")]
    class AddIisBindingCmdlet : IisApplicationCmdlet
    {
        [Parameter(Mandatory = true)]
        public string Protocol { get; set; }
        [Parameter(Mandatory = false)]
        public string HostName { get; set; }
        [Parameter(Mandatory = true)]
        public string Port { get; set; }
        [Parameter(Mandatory = false)]
        public string IPAddress { get; set; }

        protected override bool PerformActionOnSite(Site site, string serverName)
        {
            string bindingInformation =
                string.Format("{0}:{1}:{2}",
                (string.IsNullOrEmpty(this.IPAddress) == true) ? "*" : this.IPAddress,
                this.Port,
                this.HostName);

            bool found = false;

            base.Host.UI.WriteLine(string.Format("Updating bindings for {0} on {1}", site.Name, serverName));
            base.Host.UI.WriteLine(string.Format("Protocol: {0} BindingInformation: {1}", this.Protocol, bindingInformation));

            foreach (var item in site.Bindings)
            {
                if ((item.Protocol == this.Protocol) &&
                    (item.BindingInformation == bindingInformation))
                {
                    found = true;
                }
            }
            if (found == false)
            {
                site.Bindings.Add(bindingInformation, this.Protocol);
                return true;
            }
            return false;
        }
    }
}
